<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { userUploadAvatarService } from '@/api/user'
import axios from 'axios'
const userStore = useUserStore()
const uploadRef = ref()
const imgUrl = ref()
const img = ref() //后续需要传到后端的file对象
const originalFilename = ref() //原始文件名 防止生成临时查看地址的时候丢失文件名
//文件在线预览
const onUploadFile = async (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  originalFilename.value = uploadFile.raw.name
}
const onSelect = () => {
  uploadRef.value.$el.querySelector('input').click()
}
const onUpdateAvatar = async () => {
  if (!imgUrl.value) return ElMessage.error('需要先上传图片')
  img.value = await imageUrlToFile(imgUrl.value, originalFilename.value) //每次上传才将url转为File对象传输到后端去
  const fd = new FormData()
  fd.append('img', img.value)
  await userUploadAvatarService(fd)
  ElMessage.success('修改成功')
  userStore.getUser() //重新获取新的图片
}
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(
      url,
      { responseType: 'arraybuffer' },
      { headers: { 'Cache-Control': 'no-cache' } }
    )

    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}
</script>

<template>
  <page-container title="更换头像">
    <el-row>
      <el-col :span="12">
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <img v-else src="@/assets/avatar.jpg" width="278" />
        </el-upload>
        <br />
        <el-button type="primary" :icon="Plus" size="large" @click="onSelect"> 选择图片 </el-button>
        <el-button type="success" :icon="Upload" size="large" @click="onUpdateAvatar">
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </page-container>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
